use image::DynamicImage;
use webp::Encoder;
use std::fs;
use std::path::Path;
use image::ImageReader;

pub fn encode_webp(image: &DynamicImage) -> Result<Vec<u8>, String> {
    let encoder =
        Encoder::from_image(image)
        .map_err(|e| format!("Failed to create webpng encoder: {}", e))?;
    let webp_data = encoder.encode(100.0);
    Ok(webp_data.to_vec())
}

pub fn convert_image_to_webp(input_file_path: &Path, output_dir: &Option<String>) -> Result<(), String> {
    // open and decode image
    let image_render =
        ImageReader::open(input_file_path)
        .map_err(|e|format!("failed to open image: {}", e))?;
    let image = image_render
        .decode()
        .map_err(|e| format!("failed to decode image: {}", e))?;
    // image as webpng
    let webp_data = encode_webp(&image)?;
    // output
    let output_path = if let Some(output_dir) = output_dir {
        Path::new(output_dir)
            .join(input_file_path.file_stem().unwrap())
            .with_extension("webp")
    } else {
        input_file_path.with_extension("webp")
    };

    // write to system 
    fs::write(output_path.clone(), webp_data)
        .map_err(|e|format!("failed to write webp file: {}", e))?;

    println!("generated Ok: {}", output_path.display());

    Ok(())
}

fn main() {
    // testing, IMPROVE: as args
    let input_files = ["./input/1.png", "./input/2.png"];
    let output = Some("./output".to_string());

    for file in input_files.iter() {
        if let Err(e) = convert_image_to_webp(Path::new(*file), &output) {
            eprintln!("Error: {}", e);
        }
    }
}
